from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.hashers import check_password
from accounts.models import AgentInstitution, User


class SearchForm(forms.Form):
    name = forms.CharField(required=False)
    username = forms.CharField(required=False)


class LoginForm(AuthenticationForm):
    username = forms.CharField(required=True, label=u'用户名', error_messages={'required': '请输入用户名'},
                               widget=forms.TextInput(attrs={'placeholder': u'用户名'}))
    password = forms.CharField(required=True, label=u'密码', error_messages={'required': '请输入密码'},
                               widget=forms.PasswordInput(attrs={'placeholder': u'密码'}))
    remember = forms.CharField(required=False, label='记住密码', widget=forms.CheckboxInput(attrs={'value': '1'}))


class AgentInstitutionForm(forms.ModelForm):
    class Meta:
        model = AgentInstitution
        fields = ['name', 'address', 'code', 'licence_pic', 'legal_person', 'telephone', 'email', 'info']


class UserForm(forms.ModelForm):
    agent_institution = forms.ModelChoiceField(required=False, label='所属中介机构', queryset=AgentInstitution.objects.all())

    class Meta:
        model = User
        fields = ['username', 'head_pic', 'user_type', 'nick_name', 'agent_institution', 'sex', 'mobile_phone',
                  'telephone']

    def save(self, commit=True):
        self.instance.set_password('123456')
        super(UserForm, self).save(commit)
        return self.instance


class PasswordForm(forms.ModelForm):
    # old_password = forms.CharField(required=True, label='请输入旧密码',
    #                                widget=forms.PasswordInput(attrs={'placeholder': u"输入旧密码"}))
    new_password = forms.CharField(required=True, label='请输入新密码',
                                   widget=forms.PasswordInput(attrs={'placeholder': u"输入新密码"}))
    repassword = forms.CharField(required=True, label='请确认新密码',
                                 widget=forms.PasswordInput(attrs={'placeholder': u"确认密码"}))

    class Meta:
        model = User
        fields = ['new_password', 'repassword']

    def clean(self):
        cleaned_data = super(PasswordForm, self).clean()
        # old_password = cleaned_data.get("old_password")
        # v = check_password(old_password,'sha1',preferred='default')
        new_password = cleaned_data.get("new_password")
        repassword = cleaned_data.get("repassword")

        # self.instance.set_password(old_password)

        if new_password != repassword:
            self._errors["new_password"] = self.error_class([u"两个密码字段不一致。"])
        # if v != self.instance.password:
        #     self._errors["old_password"] = self.error_class([u"旧密码输入不正确。"])
        return cleaned_data


    def save(self, commit=True):
        self.instance.set_password(self.cleaned_data["new_password"])
        super(PasswordForm, self).save(commit)
        return self.instance
